import sys
import logging
sys.path.append("tweepy/".encode("utf-8"))
import tweepy
from MyModel import ManageTweetUtils
modStrConKey = "m8gDPJLNhJevZusJQ7pxA"
modStrConSec = "3CNxg3fi7GLFqAnKG9kMXBtwi8o4L7m4gEdcvA5Iw"
modStrAccKey = "28868957-BB6Cn48MwWlqkIMBIWPe97XQZ7SzBjPuCUWxmK24"
modStrAccSec = "96KjPEdIXiCtwS2SOr7U7UOQt3Slk2d5ZIdYxxdvRE"

modAuth = tweepy.OAuthHandler(modStrConKey, modStrConSec)
modAuth.set_access_token(modStrAccKey, modStrAccSec)
modTwitterApi = tweepy.API(modAuth)
modDbTweetUtilsManager = ManageTweetUtils()

#collect tweets given geocode and search terms
def CollectTweets(lstStrSearchTerms,strGeocode,intItems):
  lstOfLstsTweetValues = []
  lstOfIds = []
  InitTweetUtils()
  intLastId = GetValueFromDB("lastid")
  count = 0
  logging.info(intItems)
#  logging.info(lstStrSearchTerms)
#  logging.info(intLastId)
  for result in tweepy.Cursor(modTwitterApi.search, q= lstStrSearchTerms, since_id = intLastId, geocode = '%s,%s,%s' % (53.000, -8, '270km')).items(intItems):
    count= count +1
    lstOfLstsTweetValues.append( [result.text, result.__getstate__().get("location", "noLocat").encode("utf-8")] )
    lstOfIds.append(result.id)
  
  if sum(lstOfIds) > 0:
    WriteValueToDB( [("lastid",max(lstOfIds))])
  logging.info(lstOfLstsTweetValues )
  return lstOfLstsTweetValues 

def InitTweetUtils():
  if modDbTweetUtilsManager.CheckHasEntities() == False:
     modDbTweetUtilsManager.InitTweetUtils( [("lastid",0)] ) 
  
  else:
    return
def GetValueFromDB(strKey):
  #Return value
  return modDbTweetUtilsManager.ReturnPropertyOfTweetUtils(strKey)

def WriteValueToDB(lstUpdateValues):
  modDbTweetUtilsManager.UpdateTweetUtils(lstUpdateValues)      

